"""
Tkinter桌面UI界面
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import threading
import time
from datetime import datetime
from typing import Dict, List, Optional
import logging
from config import MONITOR_CONFIG, UI_CONFIG
from data_manager import DataManager
from pixiv_api import PixivAPI

logger = logging.getLogger(__name__)

class PixivMonitorUI:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title(UI_CONFIG["window_title"])
        self.root.geometry(UI_CONFIG["window_size"])

        # 数据管理器
        self.data_manager = DataManager()
        self.pixiv_api = PixivAPI()

        # 监控状态
        self.is_monitoring = False
        self.monitor_thread = None
        self.last_check_time = 0

        # 创建UI组件
        self._create_widgets()

        # 启动UI刷新
        self._update_ui()

    def _create_widgets(self):
        """创建UI组件"""
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # 配置行列权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(4, weight=1)

        # === 配置区域 ===
        config_frame = ttk.LabelFrame(main_frame, text="配置", padding="10")
        config_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))

        # 作者ID输入
        ttk.Label(config_frame, text="作者ID:").grid(row=0, column=0, sticky=tk.W)
        self.author_id_var = tk.StringVar()
        self.author_id_entry = ttk.Entry(config_frame, textvariable=self.author_id_var, width=15)
        self.author_id_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(5, 0))

        # 检查间隔
        ttk.Label(config_frame, text="检查间隔(分钟):").grid(row=0, column=2, sticky=tk.W, padx=(20, 0))
        self.interval_var = tk.IntVar(value=30)
        self.interval_spinbox = ttk.Spinbox(config_frame, from_=5, to=120, textvariable=self.interval_var, width=10)
        self.interval_spinbox.grid(row=0, column=3, sticky=tk.W, padx=(5, 0))

        # 添加按钮
        self.add_btn = ttk.Button(config_frame, text="添加作者", command=self._add_author)
        self.add_btn.grid(row=0, column=4, padx=(10, 0))

        # === 控制按钮 ===
        control_frame = ttk.Frame(main_frame)
        control_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))

        self.start_btn = ttk.Button(control_frame, text="开始监控", command=self._start_monitoring)
        self.start_btn.pack(side=tk.LEFT, padx=(0, 5))

        self.stop_btn = ttk.Button(control_frame, text="停止监控", command=self._stop_monitoring, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=(0, 5))

        self.check_btn = ttk.Button(control_frame, text="立即检查", command=self._check_now)
        self.check_btn.pack(side=tk.LEFT, padx=(0, 5))

        # 状态标签
        self.status_label = ttk.Label(control_frame, text="就绪")
        self.status_label.pack(side=tk.LEFT, padx=(20, 0))

        # === 作者列表 ===
        authors_frame = ttk.LabelFrame(main_frame, text="监控作者", padding="10")
        authors_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        authors_frame.columnconfigure(0, weight=1)
        authors_frame.rowconfigure(0, weight=1)

        # 作者列表 - 增加更多列
        self.author_tree = ttk.Treeview(authors_frame, columns=("id", "name", "illusts", "novels", "total", "followers", "last_update"), show="headings", height=6)
        self.author_tree.heading("id", text="ID")
        self.author_tree.heading("name", text="用户名")
        self.author_tree.heading("illusts", text="插画")
        self.author_tree.heading("novels", text="小说")
        self.author_tree.heading("total", text="总计")
        self.author_tree.heading("followers", text="粉丝数")
        self.author_tree.heading("last_update", text="最后更新")

        self.author_tree.column("id", width=60)
        self.author_tree.column("name", width=120)
        self.author_tree.column("illusts", width=50)
        self.author_tree.column("novels", width=50)
        self.author_tree.column("total", width=50)
        self.author_tree.column("followers", width=80)
        self.author_tree.column("last_update", width=120)

        # 添加滚动条
        tree_scroll = ttk.Scrollbar(authors_frame, orient=tk.VERTICAL, command=self.author_tree.yview)
        self.author_tree.configure(yscrollcommand=tree_scroll.set)

        self.author_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        tree_scroll.grid(row=0, column=1, sticky=(tk.N, tk.S))

        # 按钮框架
        btn_frame = ttk.Frame(authors_frame)
        btn_frame.grid(row=1, column=0, sticky=tk.W, pady=(5, 0))

        # 查看作品按钮
        view_btn = ttk.Button(btn_frame, text="查看作品详情", command=self._view_author_works)
        view_btn.pack(side=tk.LEFT, padx=(0, 5))

        # 刷新数据按钮
        refresh_btn = ttk.Button(btn_frame, text="刷新数据", command=self._refresh_author_data)
        refresh_btn.pack(side=tk.LEFT, padx=(0, 5))

        # 移除按钮
        remove_btn = ttk.Button(btn_frame, text="移除选中", command=self._remove_author)
        remove_btn.pack(side=tk.LEFT)

        # === 状态信息 ===
        status_frame = ttk.LabelFrame(main_frame, text="当前状态", padding="10")
        status_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))

        self.status_info_label = ttk.Label(status_frame, text="就绪")
        self.status_info_label.pack(anchor=tk.W)

        # === 变化记录 ===
        changes_frame = ttk.LabelFrame(main_frame, text="最近变化", padding="10")
        changes_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S))
        changes_frame.columnconfigure(0, weight=1)
        changes_frame.rowconfigure(0, weight=1)

        # 变化记录文本框
        self.changes_text = scrolledtext.ScrolledText(changes_frame, height=8, width=50, wrap=tk.WORD)
        self.changes_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # === 日志显示 ===
        log_frame = ttk.LabelFrame(main_frame, text="日志", padding="10")
        log_frame.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S))
        log_frame.columnconfigure(0, weight=1)
        log_frame.rowconfigure(0, weight=1)

        # 日志文本框
        self.log_text = scrolledtext.ScrolledText(log_frame, height=8, width=50, wrap=tk.WORD)
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

    def _add_author(self):
        """添加作者到监控列表"""
        author_id = self.author_id_var.get().strip()

        if not author_id:
            messagebox.showwarning("警告", "请输入作者ID")
            return

        try:
            author_id = int(author_id)
        except ValueError:
            messagebox.showerror("错误", "作者ID必须是数字")
            return

        # 检查是否已经在监控
        current_authors = self.data_manager.get_monitored_authors()
        if author_id in current_authors:
            messagebox.showinfo("提示", f"作者{author_id}已经在监控列表中")
            return

        # 测试获取作者信息
        self.status_label.config(text=f"正在测试作者{author_id}...")
        self.root.update()

        author_info = self.pixiv_api.get_author_info(author_id)
        if not author_info:
            messagebox.showerror("错误", f"无法获取作者{author_id}的信息，请检查ID和Cookie配置")
            self.status_label.config(text="就绪")
            return

        # 初始化数据
        self.data_manager.update_author_data(author_id, author_info)
        self._update_author_list()

        messagebox.showinfo("成功", f"已添加作者{author_id}到监控列表")
        self.author_id_var.set("")
        self.status_label.config(text="就绪")

    def _remove_author(self):
        """移除选中的作者"""
        selection = self.author_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请选择要移除的作者")
            return

        item = self.author_tree.item(selection[0])
        author_id = int(item['values'][0])

        if messagebox.askyesno("确认", f"确定要移除作者{author_id}的监控吗？"):
            self.data_manager.remove_author(author_id)
            self._update_author_list()
            messagebox.showinfo("成功", f"已移除作者{author_id}")

    def _start_monitoring(self):
        """开始监控"""
        if not self.data_manager.get_monitored_authors():
            messagebox.showwarning("警告", "请先添加要监控的作者")
            return

        # 跳过Cookie严格验证，直接尝试
        # if not self.pixiv_api.check_cookie_valid():
        #     messagebox.showerror("错误", "Cookie无效，请在配置文件中更新Cookie")
        #     return

        self.is_monitoring = True
        self.start_btn.config(state=tk.DISABLED)
        self.stop_btn.config(state=tk.NORMAL)
        self.status_label.config(text="监控中...")

        # 启动监控线程
        self.monitor_thread = threading.Thread(target=self._monitor_loop, daemon=True)
        self.monitor_thread.start()

        self._log("开始监控")

    def _stop_monitoring(self):
        """停止监控"""
        self.is_monitoring = False
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.status_label.config(text="已停止")

        self._log("停止监控")

    def _check_now(self):
        """立即检查所有作者"""
        if not self.data_manager.get_monitored_authors():
            messagebox.showwarning("警告", "请先添加要监控的作者")
            return

        threading.Thread(target=self._check_all_authors, daemon=True).start()

    def _monitor_loop(self):
        """监控循环"""
        while self.is_monitoring:
            try:
                self._check_all_authors()
                interval_minutes = self.interval_var.get()
                time.sleep(interval_minutes * 60)
            except Exception as e:
                logger.error(f"监控循环出错: {str(e)}")
                self._log(f"监控出错: {str(e)}")
                time.sleep(60)  # 出错后等待1分钟再重试

    def _check_all_authors(self):
        """检查所有作者"""
        authors = self.data_manager.get_monitored_authors()

        for author_id in authors:
            if not self.is_monitoring:
                break

            try:
                self.status_label.config(text=f"正在检查作者{author_id}...")
                self.status_info_label.config(text=f"正在获取作者{author_id}的数据...")
                self.root.update()

                # 获取最新数据
                author_info = self.pixiv_api.get_author_info(author_id)
                if author_info:
                    # 获取粉丝数
                    follower_count = self.pixiv_api.get_follower_count(author_id)
                    author_info["follower_count"] = follower_count

                    # 获取作品数据
                    illusts = self.pixiv_api.get_author_illusts(author_id)
                    author_info["illusts"] = illusts

                    # 更新数据并获取变化
                    changes = self.data_manager.update_author_data(author_id, author_info)

                    # 显示变化
                    if changes:
                        self._display_changes(changes)

                self.last_check_time = time.time()
                self._update_author_list()

                # 更新状态信息
                authors_data = self.data_manager.load_authors()
                if str(author_id) in authors_data:
                    author_data = authors_data[str(author_id)]
                    illusts = author_data.get("illusts", [])
                    novel_count = sum(1 for work in illusts if work.get("work_type") == "novel")
                    illust_count = sum(1 for work in illusts if work.get("work_type") == "illust")
                    total_count = len(illusts)
                    self.status_info_label.config(text=f"作者{author_id}({author_data.get('username', '未知')}): {illust_count}插画, {novel_count}小说, 总计{total_count}作品")

            except Exception as e:
                logger.error(f"检查作者{author_id}出错: {str(e)}")
                self._log(f"检查作者{author_id}出错: {str(e)}")

        self.status_label.config(text="监控中...")
        self._log("检查完成")

    def _update_author_list(self):
        """更新作者列表显示"""
        # 清空现有项目
        for item in self.author_tree.get_children():
            self.author_tree.delete(item)

        # 加载作者数据
        authors_data = self.data_manager.load_authors()

        for author_key, author_data in authors_data.items():
            last_update = author_data.get("last_update", 0)
            if last_update:
                last_update_str = datetime.fromtimestamp(last_update).strftime("%Y-%m-%d %H:%M:%S")
            else:
                last_update_str = "从未"

            # 统计作品数量
            illusts = author_data.get("illusts", [])
            novel_count = sum(1 for work in illusts if work.get("work_type") == "novel")
            illust_count = sum(1 for work in illusts if work.get("work_type") == "illust")
            total_count = len(illusts)

            self.author_tree.insert("", "end", values=(
                author_key,
                author_data.get("username", "未知"),
                illust_count,
                novel_count,
                total_count,
                author_data.get("follower_count", 0),
                last_update_str
            ))

    def _display_changes(self, changes: Dict):
        """显示变化信息"""
        timestamp = datetime.fromtimestamp(changes.get("timestamp", time.time())).strftime("%Y-%m-%d %H:%M:%S")
        author_id = changes.get("author_id")
        username = changes.get("username", f"作者{author_id}")

        text = f"[{timestamp}] {username}:\n"

        change_data = changes.get("changes", {})

        # 粉丝数变化
        if "followers" in change_data:
            follower_change = change_data["followers"]
            diff = follower_change["diff"]
            diff_str = f"+{diff}" if diff > 0 else str(diff)
            text += f"  粉丝数: {follower_change['old']} → {follower_change['new']} ({diff_str})\n"

        # 新作品
        if "new_illusts" in change_data:
            text += f"  新作品:\n"
            for illust in change_data["new_illusts"]:
                work_type = illust.get("work_type", "未知")
                type_name = "插画" if work_type == "illust" else "小说" if work_type == "novel" else "未知"
                text += f"    - {type_name}: {illust.get('title', '未知作品')} (ID: {illust.get('illust_id')})\n"

        # 作品数据更新
        if "updated_illusts" in change_data:
            text += f"  作品数据更新:\n"
            for illust in change_data["updated_illusts"]:
                work_type = illust.get("work_type", "未知")
                type_name = "插画" if work_type == "illust" else "小说" if work_type == "novel" else "未知"
                text += f"    - {type_name}: {illust.get('title', '未知作品')}:\n"
                for change_type, change_info in illust.get("changes", {}).items():
                    diff = change_info["diff"]
                    diff_str = f"+{diff}" if diff > 0 else str(diff)
                    text += f"      {change_type}: {change_info['old']} → {change_info['new']} ({diff_str})\n"

        text += "\n"

        # 插入到变化记录的开头
        self.changes_text.insert("1.0", text)
        self.changes_text.see("1.0")

        # 限制文本长度
        current_text = self.changes_text.get("1.0", tk.END)
        if len(current_text) > 10000:  # 限制10K字符
            lines = current_text.split('\n')
            # 保留前500行
            keep_text = '\n'.join(lines[:500])
            self.changes_text.delete("1.0", tk.END)
            self.changes_text.insert("1.0", keep_text)

    def _log(self, message: str):
        """添加日志"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_message = f"[{timestamp}] {message}\n"

        self.log_text.insert(tk.END, log_message)
        self.log_text.see(tk.END)

        # 限制日志长度
        current_text = self.log_text.get("1.0", tk.END)
        if len(current_text) > 5000:  # 限制5K字符
            self.log_text.delete("1.0", "2.0")

    def _update_ui(self):
        """更新UI显示"""
        # 这里可以添加定期更新UI的逻辑
        self.root.after(UI_CONFIG["refresh_interval"], self._update_ui)

    def run(self):
        """运行UI"""
        # 初始化界面
        self._update_author_list()
        self._log("Pixiv监控程序启动")

        # 检查Cookie有效性（跳过严格验证）
        # if not self.pixiv_api.check_cookie_valid():
        #     self._log("警告: Cookie可能无效，请在配置文件中更新")
        self._log("Pixiv监控程序初始化完成")

        # 运行主循环
        self.root.mainloop()

    def _view_author_works(self):
        """查看选中作者的作品详情"""
        selection = self.author_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请选择要查看的作者")
            return

        item = self.author_tree.item(selection[0])
        author_id = int(item['values'][0])
        username = item['values'][1]

        # 创建作品详情窗口
        self._create_works_window(author_id, username)

    def _refresh_author_data(self):
        """刷新选中作者的数据"""
        selection = self.author_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请选择要刷新的作者")
            return

        item = self.author_tree.item(selection[0])
        author_id = int(item['values'][0])
        username = item['values'][1]

        # 在后台线程中刷新数据
        threading.Thread(target=self._refresh_single_author, args=(author_id, username), daemon=True).start()

    def _refresh_single_author(self, author_id: int, username: str):
        """刷新单个作者的数据"""
        try:
            self.status_label.config(text=f"正在刷新{username}的数据...")
            self.status_info_label.config(text=f"正在重新获取作者{author_id}的最新数据...")
            self.root.update()

            # 获取最新数据
            author_info = self.pixiv_api.get_author_info(author_id)
            if author_info:
                # 获取粉丝数
                follower_count = self.pixiv_api.get_follower_count(author_id)
                author_info["follower_count"] = follower_count

                # 获取作品数据
                illusts = self.pixiv_api.get_author_illusts(author_id)
                author_info["illusts"] = illusts

                # 更新数据并获取变化
                changes = self.data_manager.update_author_data(author_id, author_info)

                # 显示变化
                if changes:
                    self._display_changes(changes)

                self.last_check_time = time.time()
                self._update_author_list()

                # 更新状态信息
                novel_count = sum(1 for work in illusts if work.get("work_type") == "novel")
                illust_count = sum(1 for work in illusts if work.get("work_type") == "illust")
                total_count = len(illusts)
                self.status_info_label.config(text=f"刷新完成: {username} - {illust_count}插画, {novel_count}小说, 总计{total_count}作品")
                self._log(f"刷新完成: {username} - {illust_count}插画, {novel_count}小说, 总计{total_count}作品")

            else:
                self.status_info_label.config(text=f"刷新失败: 无法获取{username}的数据")
                self._log(f"刷新失败: 无法获取{username}的数据")

        except Exception as e:
            logger.error(f"刷新作者{author_id}数据出错: {str(e)}")
            self.status_info_label.config(text=f"刷新出错: {str(e)}")
            self._log(f"刷新出错: {str(e)}")

        finally:
            self.status_label.config(text="就绪")

    def _create_works_window(self, author_id: int, username: str):
        """创建作品详情窗口"""
        # 创建新窗口
        works_window = tk.Toplevel(self.root)
        works_window.title(f"{username} 的作品详情")
        works_window.geometry("1000x700")

        # 创建主框架
        main_frame = ttk.Frame(works_window, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题标签
        title_label = ttk.Label(main_frame, text=f"{username} (ID: {author_id}) 的作品列表", font=("Arial", 14, "bold"))
        title_label.pack(pady=(0, 10))

        # 创建Notebook用于分类显示
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True)

        # 插画标签页
        ill_frame = ttk.Frame(notebook)
        notebook.add(ill_frame, text="插画作品")

        # 小说标签页
        novel_frame = ttk.Frame(notebook)
        notebook.add(novel_frame, text="小说作品")

        # 获取作品数据
        authors_data = self.data_manager.load_authors()
        works = authors_data.get(str(author_id), {}).get("illusts", [])

        # 分类作品
        illusts = [w for w in works if w.get("work_type") == "illust"]
        novels = [w for w in works if w.get("work_type") == "novel"]

        # 显示插画作品
        self._display_works_in_frame(ill_frame, illusts, "插画")

        # 显示小说作品
        self._display_works_in_frame(novel_frame, novels, "小说")

        # 底部信息
        info_frame = ttk.Frame(main_frame)
        info_frame.pack(fill=tk.X, pady=(10, 0))

        total_info = f"总计: {len(works)} 个作品 (插画: {len(illusts)}, 小说: {len(novels)})"
        ttk.Label(info_frame, text=total_info, font=("Arial", 10)).pack()

    def _display_works_in_frame(self, parent_frame, works, work_type):
        """在指定框架中显示作品列表"""
        # 创建Treeview
        columns = ("id", "title", "likes", "bookmarks", "views", "comments", "date", "tags")
        tree = ttk.Treeview(parent_frame, columns=columns, show="headings", height=15)

        # 设置列标题
        tree.heading("id", text="ID")
        tree.heading("title", text="标题")
        tree.heading("likes", text="点赞")
        tree.heading("bookmarks", text="收藏")
        tree.heading("views", text="浏览")
        tree.heading("comments", text="评论")
        tree.heading("date", text="发布时间")
        tree.heading("tags", text="标签")

        # 设置列宽
        tree.column("id", width=60)
        tree.column("title", width=200)
        tree.column("likes", width=60)
        tree.column("bookmarks", width=60)
        tree.column("views", width=60)
        tree.column("comments", width=60)
        tree.column("date", width=120)
        tree.column("tags", width=150)

        # 添加滚动条
        vsb = ttk.Scrollbar(parent_frame, orient="vertical", command=tree.yview)
        hsb = ttk.Scrollbar(parent_frame, orient="horizontal", command=tree.xview)
        tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        # 放置组件
        tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        vsb.grid(row=0, column=1, sticky=(tk.N, tk.S))
        hsb.grid(row=1, column=0, sticky=(tk.W, tk.E))

        # 配置网格权重
        parent_frame.columnconfigure(0, weight=1)
        parent_frame.rowconfigure(0, weight=1)

        # 添加作品数据
        for work in works:
            # 格式化标签
            tags_str = ", ".join(work.get("tags", [])[:5])  # 最多显示5个标签
            if len(work.get("tags", [])) > 5:
                tags_str += "..."

            # 格式化时间
            create_date = work.get("create_date", "")
            if create_date and len(create_date) > 16:
                create_date = create_date[:16]  # 只显示日期和时间部分

            tree.insert("", "end", values=(
                work.get("illust_id", ""),
                work.get("title", "未知作品"),
                work.get("like_count", 0),
                work.get("bookmark_count", 0),
                work.get("view_count", 0),
                work.get("comment_count", 0),
                create_date,
                tags_str
            ))

        # 添加双击查看详情功能
        def on_double_click(event):
            selection = tree.selection()
            if selection:
                item = tree.item(selection[0])
                work_id = item['values'][0]
                work_title = item['values'][1]
                self._show_work_detail(work_id, work_title, work_type)

        tree.bind("<Double-1>", on_double_click)

    def _show_work_detail(self, work_id: int, work_title: str, work_type: str):
        """显示单个作品的详细信息"""
        # 创建详情窗口
        detail_window = tk.Toplevel(self.root)
        detail_window.title(f"{work_title} - 详细信息")
        detail_window.geometry("600x400")

        # 创建主框架
        main_frame = ttk.Frame(detail_window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题
        title_label = ttk.Label(main_frame, text=work_title, font=("Arial", 16, "bold"))
        title_label.pack(pady=(0, 20))

        # 查找作品详细信息
        authors_data = self.data_manager.load_authors()
        work_detail = None

        for author_data in authors_data.values():
            for work in author_data.get("illusts", []):
                if work.get("illust_id") == work_id:
                    work_detail = work
                    break
            if work_detail:
                break

        if work_detail:
            # 创建信息框架
            info_frame = ttk.LabelFrame(main_frame, text="作品信息", padding="15")
            info_frame.pack(fill=tk.X, pady=(0, 20))

            # 显示详细信息
            info_items = [
                ("作品ID", work_id),
                ("作品类型", work_type),
                ("点赞数", work_detail.get("like_count", 0)),
                ("收藏数", work_detail.get("bookmark_count", 0)),
                ("浏览数", work_detail.get("view_count", 0)),
                ("评论数", work_detail.get("comment_count", 0)),
                ("发布时间", work_detail.get("create_date", "未知")),
            ]

            for label, value in info_items:
                frame = ttk.Frame(info_frame)
                frame.pack(fill=tk.X, pady=2)
                ttk.Label(frame, text=f"{label}:", font=("Arial", 10, "bold")).pack(side=tk.LEFT)
                ttk.Label(frame, text=str(value)).pack(side=tk.LEFT, padx=(10, 0))

            # 标签信息
            if work_detail.get("tags"):
                tags_frame = ttk.LabelFrame(main_frame, text="标签", padding="15")
                tags_frame.pack(fill=tk.X, pady=(0, 20))

                tags_text = ", ".join(work_detail.get("tags", []))
                ttk.Label(tags_frame, text=tags_text, wraplength=500).pack()

        # 关闭按钮
        close_btn = ttk.Button(main_frame, text="关闭", command=detail_window.destroy)
        close_btn.pack(pady=(10, 0))

    def on_closing(self):
        """关闭窗口时的处理"""
        if self.is_monitoring:
            if messagebox.askokcancel("退出", "监控正在运行，确定要退出吗？"):
                self.is_monitoring = False
                self.root.destroy()
        else:
            self.root.destroy()